//
//  PayMoneyViewController.m
//  TenThousand
//
//  Created by 王 on 16/7/16.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "PayMoneyViewController.h"
#import "MyInvestViewController.h"
#import "MyWelfareViewController.h"

@interface PayMoneyViewController ()
@property (weak, nonatomic) IBOutlet UILabel *payMoney;//支付金额
@property (weak, nonatomic) IBOutlet UILabel *ProjectName;//产品名称
@property (weak, nonatomic) IBOutlet UILabel *Term;//期限
@property (weak, nonatomic) IBOutlet UILabel *Rate;//预期年化收益
@property (weak, nonatomic) IBOutlet UILabel *InvestmentAmount;//投资金额

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *Income;//万元收益
@property (weak, nonatomic) IBOutlet UILabel *yujishouyi;

@property (nonatomic, strong) NSString *waterNumber;
@property (weak, nonatomic) IBOutlet UILabel *UseRedBag;


@end

@implementation PayMoneyViewController
{
    NSInteger   aititude;
    NSString    *redBAGID;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    self.title = @"确认投资";
    
    [self createLeft:[UIImage imageNamed:@"ZHSZicon_03"] leftClick:^{
        [self.navigationController popViewControllerAnimated:NO];
    } right:nil rightClick:nil];
    
    
    [self setDataWithModel:nil];
    
    
    [self createLeft:[UIImage imageNamed:@"ZHSZicon_03"] leftClick:^{
        [self.navigationController popViewControllerAnimated:NO];
    } right:nil rightClick:nil];
    
    self.ProjectName.text = [NSString stringWithFormat:@"%@%@",self.model.ProjectName,self.model.Code];
    self.Term.text = [NSString stringWithFormat:@"%@",self.model.Term];
    self.Rate.text = [NSString stringWithFormat:@"%.2f",self.model.Rate];
    self.InvestmentAmount.text = [NSString stringWithFormat:@"%@元",self.money];
    
    self.UseRedBag.userInteractionEnabled=YES;
    UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTouchUpInside:)];
    
    [self.UseRedBag addGestureRecognizer:labelTapGestureRecognizer];
   
    [self getRecognition];
    
    
    NSLog(@"%@==",self.waterNumber);
   
}

#pragma mark --- 跳转红包界面
-(void) labelTouchUpInside:(UITapGestureRecognizer *)recognizer{
    
    MyInvestViewController *vc = [[MyInvestViewController alloc]init];
    vc.num = 6;
    vc.redMoney = _InvestmentAmount.text;
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    
    [center addObserver:self selector:@selector(notice:) name:@"123" object:nil];
    
    [self.navigationController pushViewController:vc animated:YES];

}

-(void)notice:(NSNotification *)notification{
    [self.navigationController popViewControllerAnimated:YES];
    NSLog(@"%@",[notification.userInfo objectForKey:@"money"]);
    NSLog(@"%@",[notification.userInfo objectForKey:@"redID"]);
    self.UseRedBag.text = [NSString stringWithFormat:@"%.2f",[[notification.userInfo objectForKey:@"money"] doubleValue]];
    self.payMoney.text = [NSString stringWithFormat:@"%.2f",[self.money doubleValue] - [[notification.userInfo objectForKey:@"money"] doubleValue]];
    redBAGID = [notification.userInfo objectForKey:@"redID"];
    aititude =1;
}


-(BorrowGetDetailModel *)model{
    if (!_model) {
        _model = [[BorrowGetDetailModel alloc] init];
    }
    return _model;
}

//确认投资
- (void)getRecognition{
    
    /**
     *  BrrowId 借款编号 
     *  Amount  投资金额
     *  LoginName 用户账号
     */
    NSString *LoginName = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginName"];
    
    
    NSDictionary *para = @{
                            @"LoginName":LoginName,
                            @"Amount":self.money,
                            @"BrrowId":self.model.BorrowId,
                            @"HongBaoId":@"0"
                           };
    
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Invest.GetRecognition" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@",object);
        //返回流水号
        if ([object[@"Code"] isEqualToString:@"00000"]) {
            for (NSDictionary *dic in object[@"Data"]) {
                NSString *WaterNumber = dic[@"WaterNumber"];
                self.waterNumber = WaterNumber;
               
                
               [self getSearchPofit];//查询预计收益


            }

        }else {
            [ToastView showInfoWithStatus:object[@"Message"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@",error);
    } progress:nil];
}


- (IBAction)payMoney:(id)sender {
    if (aititude ==1) {
        NSDictionary *para = @{
                               @"RedMoneyId":redBAGID,
                               @"WaterNumber":self.waterNumber,
                               };
        
        [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Users.GetUpdateBao" withParaments:para withSuccessBlock:^(NSDictionary *object) {
            NSLog(@"%@",object);
            if ([object[@"Code"] isEqualToString:@"00000"]) {
                //            [ToastView showInfoWithStatus:object[@"Message"]];
                [self FengFu:self.waterNumber];
            }else
                [ToastView showInfoWithStatus:object[@"Message"]];
        } withFailureBlock:^(NSError *error) {
            NSLog(@"%@",error);
        } progress:nil];

    }else {
        [self FengFu:self.waterNumber];
    }
    
    
}

- (void)FengFu:(NSString *)requestId {//用户投标
    


    
    
    NSString *LoginId = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginId"];
    
    NSString *subledgerList = nil;
    NSString    *useRed = nil;
    if (aititude == 1) {
        subledgerList = [NSString stringWithFormat:@"[{\"roleType\":\"1\",\"roleCode\":\"%@\",\"inOrOut\":\"1\",\"sum\":\"%.2f\",\"bizFlag\":\"2\"},{\"roleType\":\"0\",\"roleCode\":\"%@\",\"inOrOut\":\"1\",\"sum\":\"%.2f\",\"bizFlag\":\"0\"}]", FengFuMerchantCode, [self.UseRedBag.text floatValue],LoginId,[self.payMoney.text floatValue]];
        useRed = @"1";
    }else {
        subledgerList = [NSString stringWithFormat:@"[{\"roleType\":\"0\",\"roleCode\":\"%@\",\"inOrOut\":\"1\",\"sum\":\"%.2f\",\"bizFlag\":\"0\"}]", LoginId,[self.money floatValue]];
        useRed = @"";
    }
    NSDictionary *dic = @{
                          @"requestType":@"PFT0003",
                          @"requestId":requestId,
                          @"merchantCode":FengFuMerchantCode,
                          @"userIdIdentity":LoginId,
                          @"sum":self.money,//投标金额
                          @"projectCode":self.model.BorrowId,//项目编号
                          @"projectDescription":@"",//项目描述
                          @"projectSum":[NSString stringWithFormat:@"%.2f", self.model.TotalAmount],//项目总额
                          @"giftFlag":useRed,//红包标识
                          @"subledgerList":subledgerList,//分账列表
                          @"noticeUrl":[NSString stringWithFormat:@"%@API/notice/jktbnotice.aspx", noticeUrl],
                          @"successReturnUrl":@"",
                          @"failReturnUrl":@"",
                          };
    NSString *sign = [[[[[[[[[[[[dic[@"requestType"] stringByAppendingString:dic[@"requestId"]] stringByAppendingString:dic[@"merchantCode"]] stringByAppendingString:dic[@"userIdIdentity"]] stringByAppendingString:dic[@"sum"]] stringByAppendingString:dic[@"projectCode"]] stringByAppendingString:dic[@"projectDescription"]] stringByAppendingString:dic[@"projectSum"]] stringByAppendingString:dic[@"giftFlag"]] stringByAppendingString:dic[@"subledgerList"]] stringByAppendingString:dic[@"noticeUrl"]] stringByAppendingString:dic[@"successReturnUrl"]] stringByAppendingString:dic[@"failReturnUrl"]];
    NSString *signature = [HMACMD5 HMACMD5WithString:sign WithKey:FengFuKEY];
    NSDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
    [dict setValue:signature forKey:@"signature"];
    [SumaPaySDK startService:dict callback:^(id resultDic, NSError *error) {
        NSLog(@"%@--------------%@", resultDic, error);
        NSDictionary *dic1 = [NetWorkManager dictionaryWithJsonString:resultDic];
        if ([dic1[@"result"] integerValue] == 0) {
            if ([dic1[@"msg"][@"result"] integerValue] == 00000) {
                [self getSureRecognition];
            } else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
}

//确认投资   去付款
-(void)getSureRecognition{
    
    
    NSString *LoginId = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginId"];
    
    NSDictionary *para = @{
                           @"Amount":self.money,
                           @"Borrowid":self.model.BorrowId,
                           @"LoginId":LoginId,
                           @"WaterNumber":self.waterNumber
                           };
    NSLog(@"投资%@",para);
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Invest.GetSureRecognition" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"投资%@",object);
        if ([object[@"Code"] integerValue] == 00000) {
            [ToastView showSuccessWithStatus:object[@"Message"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@",error);
    } progress:nil];
}


//页面信息展示
-(void)setDataWithModel:(BorrowGetDetailModel *)model{
    _payMoney.text = [NSString stringWithFormat:@"%.2f元",[self.money floatValue]];//支付金额
    _InvestmentAmount.text = [NSString stringWithFormat:@"%.2f元",[self.money floatValue]];//投资金额
}

-(void)getSearchPofit{
    
    NSDictionary *para = @{
                           @"WaterNumber":self.waterNumber
                           };
    
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Invest.GetSearchPofit" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        _yujishouyi.text = [NSString stringWithFormat:@"%.2f",[[object[@"Data"] firstObject][@"Pofit"] floatValue]];
        
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@==",error);
    } progress:nil];
}





@end
